<template>
  <div class="el-main">
    <el-form ref="form" :model="doctor" :rules="rules"  label-width="120px">
      <el-form-item label="医生名称" prop="name">
        <el-input v-model="doctor.name"></el-input>
      </el-form-item>
      <el-form-item label="研究方向" prop="research">
        <el-input v-model="doctor.research"></el-input>
      </el-form-item>
      <el-form-item label="职称" prop="title">
        <el-input v-model="doctor.title"></el-input>
      </el-form-item>
      <el-form-item label="照片">
        <el-upload
          :action="posterUrl"
          :before-upload="beforeUpload"
          :limit="1"
          :http-request="(params)=>uploadImage(params)"
          :on-remove="(file, fileList)=>removeImage(file, fileList)"
          list-type="picture"
          accept="image/*">
          <el-button size="small">选择图片</el-button>
        </el-upload>
        <img v-show="false" :src="'http://47.105.63.191:8888/imgUrl/'+doctor.photo.split('/')[3]" width="135"
             height="201"/>
      </el-form-item>
      <el-form-item label="所属科室" prop="departmentId" align="left">
        <el-select v-model="doctor.departmentId" placeholder="请选择所属科室">
          <template v-for="(item,index) in departmentList">
            <el-option :label="item.name" :key="item.id" :value="item.id"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="是否是知名专家" prop="isFamousExpert" align="left">
        <el-switch v-model="doctor.isFamousExpert" :active-value="1" inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="简介" prop="introduce">
        <el-input v-model="doctor.introduce" type="textarea"></el-input>
      </el-form-item>
      <el-form-item style="padding-top: 50px" prop="type">
        <el-input v-show="false" v-model="doctor.type"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="exit()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {uploadImgToBase64} from '@/utils/fileUtils'
  import Qs from 'qs';

  export default {
    name: "doctorAdd",
    data() {
      return {
        parentId: 0,
        //options: [],
        departmentList: [],
        fileList: [],
        departmentId: '',
        posterUrl: '',
        imgUrls: [],
        imgWidth: '320',
        imgHeight: '400',
        imgBroadcastList: [], // 储存选中   的图片列表
        doctor: {
          name: "",
          research: "",
          title: "",
          introduce: "",
          isFamousExpert: 0,
          departmentId:"",
          departmentName: "",
          photo: ''   // 后端需要的多张图base64字符串 , 分割
        },
        rules:{
          name: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
          ],
          departmentId: [
            { type: 'array', required: true, message: '至少选择一个科室', trigger: 'change' }
          ],
        }
      }
    },
    methods: {
      handleChange(value) {
        console.log(value);
      },
      findAll() {
        let data = Qs.stringify({parentId: this.parentId})
        this.instance.get('/w/departments/findAll'
        ).then(data => {
          this.departmentList = data.data;
        })
      },
      onSubmit() {
        let that = this;
        this.instance.post('/w/doctors', this.doctor)
          .then(function (response) {
            that.$router.push({name: 'doctor'})
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      beforeUpload(file) {
        let _this = this;
        let _checkSize = false; //是否需要指定上传图片的尺寸
        if (file.size > 1024 * 1000) { //大小超过500kb
          _this.$message.error('图片太大，请重新选择');
          return false;
        }
        const isSize = new Promise((resolve, reject) => {
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            if (!_checkSize || (_checkSize && img.width == _this.imgWidth && img.height == _this.imgHeight)) {
              resolve();
            } else {
              reject();
            }
          }
          img.src = _URL.createObjectURL(file);
        }).then(() => {
          return file;
        }, () => {
          _this.$message.error('图片尺寸不对，请重新选择');
          return Promise.reject();
        });
        return isSize;
      },

      uploadImage(params) {

        let uploadData = new FormData();
        uploadData.append('file', params.file);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };
        this.uploadPoster('homed' + new Date().getTime() + '/' + params.file.name, uploadData, config)

      },

      removeImage(file, fileList) {
        console.log(fileList);
      },

      uploadPoster(url, obj, config) {
        let that = this;
        let poster_upload_path = "/w/doctors/upload";
        debugger
        that.instance.post(poster_upload_path, obj, config).then(function (res) {
          debugger
          console.log(res)
          that.doctor.photo = res[0].url;
        })

      },
      exit() {
        this.$router.push({name: 'doctor'}) // 只能用 name
      }

    },
    mounted() {

    },
    created() {
      let that = this;
      //that.getMenus();
      that.findAll();
      if (!!that.$route.query.doctor) {
        that.doctor = that.$route.query.doctor
        that.departmentId = that.doctor.departmentId;
        that.doctor.departmentId = Number(that.departmentId)
      }
    }
  }
</script>

<style scoped lang="scss">

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
